package com.gx.interceptor;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import java.util.Properties;
import java.util.concurrent.Executor;

@Intercepts({
        @Signature(type = org.apache.ibatis.executor.Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class })
})
public class SqlLogMybatisInterceptor implements Interceptor {
    private Logger log = LoggerFactory.getLogger(SqlLogMybatisInterceptor.class);
    private static ThreadLocal<String> keyId = new ThreadLocal<String>();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        Object mybatisSql = null;

        log.info("mappedStatement："+ JSON.toJSONString(mappedStatement));
        log.info("parameter："+ JSON.toJSONString(parameter));
        log.info("sqlId："+ JSON.toJSONString(sqlId));
        log.info("boundSql："+ JSON.toJSONString(boundSql));
        log.info("configuration："+ JSON.toJSONString(configuration));

        return mybatisSql;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }
}
